#include "sniffer.h"
#include "appglobal.h"
#include "diskmap.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QRegExp>
#include <QDebug>
#include <QStringList>
#include <QFile>
#include <QTime>

YDBaiduDiskSniffer::YDBaiduDiskSniffer(QObject* parent)
    : YDSniffer(parent) {
}

YDBaiduDiskSniffer::~YDBaiduDiskSniffer() {
}

void YDBaiduDiskSniffer::sniff(const YDSniffer::job_t& job) {
    QNetworkAccessManager* mgr = g.networkAccessMgr;

    this->map.clear();

    for (auto s : job) {
        qDebug() << "url to be sniffed: " << s;
        QNetworkRequest req(s);
        req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT6.0)");
        QNetworkReply* reply = mgr->get(req);
        void (QNetworkReply::*sig)(QNetworkReply::NetworkError) = &QNetworkReply::error;

        reply->setReadBufferSize(0);
        connect(reply, sig,
            this, &YDBaiduDiskSniffer::on_reply_error);
        connect(reply, &QNetworkReply::finished,
            this, &YDBaiduDiskSniffer::on_reply_finished);
        this->map[reply] =s;
    }
}

void YDBaiduDiskSniffer::on_reply_error(QNetworkReply::NetworkError) {
    QNetworkReply* reply = reinterpret_cast<QNetworkReply*>(this->sender());

    emit this->error(this->map[reply]);
    reply->deleteLater();
}

void YDBaiduDiskSniffer::on_reply_finished() {
    QNetworkReply* reply = reinterpret_cast<QNetworkReply*>(this->sender());
    QByteArray array = reply->readAll();
    QString str = QString::fromUtf8(array);

#ifndef NDEBUG
    QString filename = "C:\\ydhelperdebug\\" + QTime::currentTime().toString("hh_mm_ss_zzz") + ".log";
    QFile f(filename, this);
    f.open(QIODevice::ReadWrite);
    qDebug() << f.isWritable();
    f.write(array);
    f.close();
#endif

    QString realUrl = this->analyze(str);
    qDebug() << "Url: " << this->map[reply];
    qDebug() << "Real Url: " << realUrl;

    if (!realUrl.isEmpty()) {
        emit this->getUrl(this->map[reply], realUrl);
    } else {
        emit this->error(this->map[reply]);
    }

    reply->deleteLater();
}

QString YDBaiduDiskSniffer::analyze(const QString& str) {
    QRegExp* reg = g.diskMap->getRealUrlReg(this->type());
    qDebug() << "pattern: " << reg->pattern();

    int pos = reg->indexIn(str);
    QString ret;

    if (pos >= 0) {
        ret = reg->cap(1);
    }

    return ret;
}
